import 'dart:async';

import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/event/WkEventListener.dart';
import 'package:wk_robot2/app/widget/CommonWidgets.dart';
import '../../../blt/BltManager.dart';
import '../../../blt/RobotCommands.dart';
import '../../../event/DataCallBack.dart';
import '../../../routes/app_pages.dart';
import '../../../widget/tips.dart';
import '../../bindtip/views/bindtip_view.dart';

class DeviceConnectionController extends GetxController {

  var showTips = false.obs;
  var isHasManual = false.obs;

  bool hasJump2Connection = false;

  bool fromAutoConnectingPage = false;

  bool toStopScan = false;
  bool timeout_60s = false;


  bool justShowOnce = false;

  @override
  void onInit() {
    super.onInit();

    FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
      print(state);
      if (state == BluetoothAdapterState.on) {
        // usually start scanning, connecting, etc
      } else {

        if (!justShowOnce) {
          justShowOnce = true;
          // show an error to the user, etc
          CommonWidgets.showSingleBtnDialog(Get.context!, '', '手机蓝牙已关闭.', WkEventListener(
              onClick: (v) {
                justShowOnce = false;
              }
          ));
        }


      }
    });

  }

  @override
  void onReady() {
    super.onReady();

  }

  @override
  void onClose() {
    super.onClose();

  }

  void setAutoOrManualConnected(bool auto) {
    fromAutoConnectingPage = auto;
  }


  void setToStopCan(bool stopScan) {
     toStopScan = stopScan;
  }

  void startAutoScan() {
    timeout_60s = false;
     // 60s总扫描时间,如果仍然无法找到设备,则弹框提示.
    Future.delayed(Duration(seconds: 60),() {
      timeout_60s = true;
      if (EasyLoading.isShow) { // 说明没有找到机器人.
        stopScan();
        showTips.value = true;
        if (!isHasManual.value)
        CommonWidgets.showDialogForAssistantHelp(Get.context!);
      }

    });

    startScan();
  }


  void startScan() {
    isHasManual.value = false;
    hasJump2Connection = false;
    //toStopScan = false;

    if(toStopScan) {
      return;
    }

    Future.delayed(Duration(seconds: 2),() {
      if (isHasManual.value) {
        return;
      }
      FlutterBluePlus.stopScan();

      Tips.showLoading();

      BltManager.instance.toScan(dataCallBack: DataCallBack(
        deviceCallBack: (param) {

          Tips.dismissLoading();

          if (toStopScan) {
            return;
          }

          if (hasJump2Connection) {
            return;
          }

          if (!hasJump2Connection) {
            hasJump2Connection = true;
          }

          FlutterBluePlus.stopScan();

          setAutoOrManualConnected(true);
          //设备连接成功.
          Get.toNamed(Routes.CONNECT_SUCESS);
        },
        errorCallBack: (info) {

          Tips.dismissLoading();

          if (toStopScan) {
            return;
          }

          //没有找到设备.
          if (HardwareCommands.SCAN_DEVICE_ERROR_NO_FOUND == info) {
            showTips.value = true;
          } else if(info == HardwareCommands.SCAN_DEVICE_RECONNECTED) {
            //重新扫描.
            Future.delayed(Duration(seconds: 1),() {
                 if (timeout_60s) { //超时的话就不会再进行扫描了.
                   return;
                 }
                 startScan();
            });
            // startScan();
          } else {
            Get.toNamed(Routes.BINDTIP,arguments: {
              'type': ERROR_NO_FOUND_SERVICES
            });
          }

        },

      ), timeout: 5);
    });

  }


  void stopScan() {
    toStopScan = true;
    FlutterBluePlus.stopScan();
    if (EasyLoading.isShow) {
      Tips.dismissLoading();
    }

    Future.delayed(Duration(seconds: 2),() {
      if (EasyLoading.isShow) {
        Tips.dismissLoading();
        Future.delayed(Duration(seconds: 2),() {
          if (EasyLoading.isShow) {
            Tips.dismissLoading();
          }
        });
      }
    });


  }

  void goToManualConnect() {
    stopScan();
    isHasManual.value = true;
    Get.toNamed(Routes.MANUAL_CONNECTION);
  }
}
